package com.eshop.modules.security.service;

import java.util.Date;
import com.eshop.modules.security.security.vo.JwtUser;
import com.eshop.modules.system.service.dto.JobSmallDto;
import java.util.function.Function;
import com.eshop.modules.system.service.dto.DeptSmallDto;
import java.util.Optional;
import com.eshop.modules.system.service.dto.UserDto;
import com.eshop.exception.BadRequestException;
import org.springframework.security.core.userdetails.UserDetails;
import com.eshop.modules.system.service.RoleService;
import com.eshop.modules.system.service.UserService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;
import org.springframework.security.core.userdetails.UserDetailsService;

@Service("userDetailsService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = { Exception.class })
public class UserDetailsServiceImpl implements UserDetailsService
{
    private final UserService userService;
    private final RoleService roleService;
    
    public UserDetailsServiceImpl(final UserService userService, final RoleService roleService) {
        this.userService = userService;
        this.roleService = roleService;
    }
    
    public UserDetails loadUserByUsername(final String username) {
        final UserDto user = this.userService.findByName(username);
        if (user == null) {
            throw new BadRequestException("账号不存在");
        }
        if (!user.getEnabled()) {
            throw new BadRequestException("账号未激活");
        }
        return this.createJwtUser(user);
    }
    
    private UserDetails createJwtUser(final UserDto user) {
        return (UserDetails)new JwtUser(user.getId(), user.getUsername(), user.getNickName(), user.getSex(), user.getPassword(), user.getAvatar(), user.getEmail(), user.getPhone(), Optional.ofNullable(user.getDept()).map((Function<? super DeptSmallDto, ? extends String>)DeptSmallDto::getName).orElse(null), Optional.ofNullable(user.getJob()).map((Function<? super JobSmallDto, ? extends String>)JobSmallDto::getName).orElse(null), this.roleService.mapToGrantedAuthorities(user), user.getEnabled(), user.getCreateTime(), user.getLastPasswordResetTime());
    }
}
